// 脚本状态管理 - 从原始 scriptManager.js 简化版本
import { defineStore } from 'pinia'

export const useScriptStore = defineStore('script', {
  state: () => ({
    currentScript: '',
    steps: [],
    scriptFormat: 'playwright', // 'playwright' | 'jsonl'
    isRecording: false,
    scriptName: 'login_test',
    metadata: {
      startUrl: '',
      language: 'javascript',
      totalSteps: 0
    }
  }),

  getters: {
    stepCount: (state) => state.steps.length,
    hasSteps: (state) => state.steps.length > 0,
    formatDisplay: (state) => state.scriptFormat === 'playwright' ? 'Playwright' : 'JSONL'
  },

  actions: {
    // 导入脚本
    importScript(content, filename = '') {
      try {
        this.currentScript = content
        
        // 根据文件名或内容推断格式
        if (filename.endsWith('.jsonl') || filename.endsWith('.json') || content.trim().startsWith('{')) {
          this.scriptFormat = 'jsonl'
        } else {
          this.scriptFormat = 'playwright'
        }
        
        // 从文件名中提取脚本名称
        if (filename) {
          this.scriptName = filename.replace(/\.(js|ts|jsonl|json|py)$/, '')
        }
        
        this.parseStepsFromScript(content, this.scriptFormat)
        return { success: true }
      } catch (error) {
        console.error('导入脚本失败:', error)
        throw new Error(error.message)
      }
    },

    // 从录制导入步骤
    importStepsFromRecording(recordingSteps, metadata = {}) {
      try {
        console.log('从录制导入步骤:', recordingSteps.length, '个步骤')
        
        // 清空现有步骤
        this.steps = []
        
        // 转换录制步骤为脚本步骤格式
        this.steps = recordingSteps.map((step, index) => ({
          stepNumber: index + 1,
          type: step.type || 'unknown',
          action: step.type || 'unknown',
          description: step.description || step.name || `步骤 ${index + 1}`,
          selector: step.selector || '',
          value: step.value || '',
          url: step.url || '',
          timeout: step.timeout || 5000,
          delay: step.delay || 1000,
          status: 'pending',
          originalCode: step.originalCode || '',
          timestamp: step.timestamp || new Date().toISOString()
        }))
        
        // 更新元数据
        this.scriptName = metadata.name || `录制脚本_${new Date().toLocaleString()}`
        this.scriptFormat = 'recording'
        this.metadata = {
          ...this.metadata,
          ...metadata,
          totalSteps: this.steps.length,
          importTime: new Date(),
          source: 'recording'
        }
        
        console.log('录制步骤导入完成:', this.steps.length, '个步骤')
        
        // 触发步骤导入事件
        if (typeof window !== 'undefined') {
          const importEvent = new CustomEvent('stepsImported', {
            detail: {
              steps: this.steps,
              metadata: this.metadata,
              source: 'recording'
            }
          })
          document.dispatchEvent(importEvent)
        }
        
        return { success: true, steps: this.steps }
      } catch (error) {
        console.error('从录制导入步骤失败:', error)
        throw new Error(error.message)
      }
    },

    // 解析步骤 - 使用与recordingManager相同的解析逻辑
    parseStepsFromScript(content, format) {
      const steps = []
      
      if (format === 'playwright') {
        // 使用与recordingManager相同的解析逻辑
        steps.push(...this.parsePlaywrightScript(content))
      } else if (format === 'jsonl') {
        // 解析 JSONL 格式
        const lines = content.split('\n').filter(line => line.trim())
        lines.forEach(line => {
          try {
            const stepData = JSON.parse(line)
            steps.push({
              ...stepData,
              status: 'pending'
            })
          } catch (error) {
            console.warn('解析JSONL行失败:', line, error)
          }
        })
      }
      
      this.steps = steps
      this.metadata.totalSteps = steps.length
      
      // 触发步骤导入事件
      if (typeof window !== 'undefined') {
        const importEvent = new CustomEvent('stepsImported', {
          detail: {
            steps: this.steps,
            metadata: this.metadata,
            source: 'import'
          }
        })
        document.dispatchEvent(importEvent)
      }
    },

    // 解析Playwright脚本
    parsePlaywrightScript(scriptContent) {
      const steps = []
      
      if (!scriptContent || typeof scriptContent !== 'string') {
        return steps
      }
      
      const lines = scriptContent.split('\n')
      let stepIndex = 0
      let inAsyncFunction = false
      
      for (let i = 0; i < lines.length; i++) {
        const line = lines[i].trim()
        
        // 跳过空行、注释、导入语句、函数定义等
        if (!line || line.startsWith('//') || line.startsWith('import') || 
            line.startsWith('const {') || line.startsWith('test(') || 
            line === '}' || line === '});' || line === '{' ||
            line.startsWith('(async () => {') || line.startsWith('})();')) {
          
          if (line.startsWith('(async () => {')) {
            inAsyncFunction = true
          }
          continue
        }
        
        // 跳过函数外的代码
        if (!inAsyncFunction) {
          continue
        }
        
        // 跳过变量赋值和Promise处理
        if (line.includes('=') && (line.includes('waitForEvent') || line.includes('Promise'))) {
          continue
        }
        
        // 只解析关键操作
        const step = this.parseLineToStep(line, stepIndex)
        if (step) {
          steps.push({
            ...step,
            status: 'pending',
            originalCode: line,
            timestamp: new Date().toISOString()
          })
          stepIndex++
        }
      }
      
      return steps
    },

    // 解析单行代码为步骤
    parseLineToStep(line, stepIndex) {
      const cleanLine = line.replace(/^\s*await\s+/, '').replace(/;?\s*$/, '')
      
      // 1. 导航操作 - page.goto()
      if (cleanLine.includes('.goto(')) {
        const urlMatch = cleanLine.match(/\.goto\(['"`]([^'"`]+)['"`]\)/)
        return {
          stepNumber: stepIndex + 1,
          type: 'navigation',
          name: '导航到页面',
          description: `打开网页: ${urlMatch ? urlMatch[1] : ''}`,
          url: urlMatch ? urlMatch[1] : '',
          action: 'goto'
        }
      }
      
      // 2. 通过角色点击 - getByRole().click()
      if (cleanLine.includes('.getByRole(') && cleanLine.includes('.click()')) {
        const roleMatch = cleanLine.match(/\.getByRole\(['"`]([^'"`]+)['"`],\s*\{\s*name:\s*['"`]([^'"`]+)['"`]\s*\}\)/)
        if (roleMatch) {
          return {
            stepNumber: stepIndex + 1,
            type: 'click',
            name: '点击链接',
            description: `点击${roleMatch[1]}: ${roleMatch[2]}`,
            elementName: roleMatch[2],
            action: 'click'
          }
        }
      }
      
      // 3. 通过定位器点击 - locator().click()
      if (cleanLine.includes('.locator(') && cleanLine.includes('.click()')) {
        // 处理文本过滤点击
        if (cleanLine.includes('.filter(')) {
          const filterMatch = cleanLine.match(/\.locator\(['"`]([^'"`]+)['"`]\)\.filter\(\{\s*hasText:\s*\/([^\/]+)\/\s*\}\)/)
          if (filterMatch) {
            return {
              stepNumber: stepIndex + 1,
              type: 'click',
              name: '点击文本元素',
              description: `点击包含"${filterMatch[2]}"的${filterMatch[1]}`,
              textContent: filterMatch[2],
              action: 'click'
            }
          }
        }
        
        // 处理链式定位器点击
        if (cleanLine.includes('.getByRole(')) {
          const chainMatch = cleanLine.match(/\.locator\(['"`]([^'"`]+)['"`]\)\.getByRole\(['"`]([^'"`]+)['"`],\s*\{\s*name:\s*['"`]([^'"`]+)['"`],\s*exact:\s*true\s*\}\)/)
          if (chainMatch) {
            return {
              stepNumber: stepIndex + 1,
              type: 'click',
              name: '点击精确链接',
              description: `在${chainMatch[1]}中点击: ${chainMatch[3]}`,
              elementName: chainMatch[3],
              action: 'click'
            }
          }
        }
      }
      
      // 4. 输入操作 - fill() 或 type()
      if (cleanLine.includes('.fill(') || cleanLine.includes('.type(')) {
        // 处理通过getByRole调用的fill操作
        if (cleanLine.includes('.getByRole(') && cleanLine.includes('.fill(')) {
          const roleFillMatch = cleanLine.match(/\.getByRole\(['"`]([^'"`]+)['"`],\s*\{\s*name:\s*['"`]([^'"`]+)['"`]\s*\}\)\.fill\(['"`]([^'"`]*)['"`]\)/)
          if (roleFillMatch) {
            return {
              stepNumber: stepIndex + 1,
              type: 'input',
              name: '输入文本',
              description: `在${roleFillMatch[1]}中输入: ${roleFillMatch[3]}`,
              elementName: roleFillMatch[2],
              value: roleFillMatch[3],
              action: 'fill'
            }
          }
        }
        
        // 处理通过选择器调用的fill操作
        const matches = cleanLine.match(/\.(fill|type)\(['"`]([^'"`]+)['"`],\s*['"`]([^'"`]*)['"`]\)/)
        if (matches) {
          return {
            stepNumber: stepIndex + 1,
            type: 'input',
            name: '输入文本',
            description: `在${matches[2]}中输入: ${matches[3]}`,
            value: matches[3],
            selector: matches[2],
            action: matches[1]
          }
        }
      }
      
      // 5. 关闭操作 - close() (跳过不展示)
      if (cleanLine.includes('.close()')) {
        return null
      }
      
      return null
    },

    // 导出脚本
    exportScript(options = {}) {
      const targetFormat = options.format || this.scriptFormat
      const scriptName = options.name || this.scriptName
      let content = ''
      let filename = ''
      
      if (targetFormat === 'playwright') {
        content = this.exportToPlaywright()
        filename = `${scriptName}.js`
      } else if (targetFormat === 'jsonl') {
        content = this.exportToJsonl()
        filename = `${scriptName}.jsonl`
      }
      
      return {
        content,
        filename,
        format: targetFormat
      }
    },

    // 导出为 Playwright 格式
    exportToPlaywright() {
      let script = `import { test, expect } from '@playwright/test';\n\n`
      script += `test('${this.scriptName}', async ({ page }) => {\n`
      
      this.steps.forEach(step => {
        if (step.originalCode) {
          script += `  ${step.originalCode}\n`
        } else {
          // 根据步骤类型生成代码
          switch (step.type) {
            case 'navigation':
              script += `  await page.goto('${step.url}');\n`
              break
            case 'input':
              script += `  await page.fill('${step.selector}', '${step.value}');\n`
              break
            case 'click':
              script += `  await page.click('${step.selector}');\n`
              break
            case 'assertion':
              script += `  await expect(page.locator('${step.selector}')).toBeVisible();\n`
              break
          }
        }
      })
      
      script += '});'
      return script
    },

    // 导出为 JSONL 格式
    exportToJsonl() {
      return this.steps.map(step => JSON.stringify({
        stepNumber: step.stepNumber,
        type: step.type,
        action: step.action,
        description: step.description,
        selector: step.selector,
        value: step.value,
        url: step.url,
        originalCode: step.originalCode,
        timestamp: step.timestamp || new Date().toISOString()
      })).join('\n')
    },

    // 保存脚本
    async saveScript() {
      try {
        // 这里可以添加真实的保存逻辑，比如保存到本地存储或服务器
        const scriptData = {
          name: this.scriptName,
          format: this.scriptFormat,
          steps: this.steps,
          metadata: this.metadata,
          lastModified: new Date().toISOString()
        }
        
        // 保存到localStorage作为演示
        localStorage.setItem(`script_${this.scriptName}`, JSON.stringify(scriptData))
        
        return { success: true, message: '脚本已保存' }
      } catch (error) {
        console.error('保存脚本失败:', error)
        throw new Error(error.message)
      }
    },

    // 清空步骤
    clearSteps() {
      this.steps = []
      this.currentScript = ''
      this.metadata.totalSteps = 0
    },

    // 添加步骤
    addStep(stepData) {
      const step = {
        stepNumber: this.steps.length + 1,
        status: 'pending',
        ...stepData
      }
      this.steps.push(step)
      this.metadata.totalSteps = this.steps.length
    },

    // 更新步骤
    updateStep(stepIndex, updatedStep) {
      if (stepIndex >= 0 && stepIndex < this.steps.length) {
        this.steps[stepIndex] = {
          ...this.steps[stepIndex],
          ...updatedStep
        }
        
        // 触发步骤更新事件
        if (typeof window !== 'undefined') {
          const event = new CustomEvent('stepUpdated', {
            detail: {
              index: stepIndex,
              step: this.steps[stepIndex]
            }
          })
          document.dispatchEvent(event)
        }
        
        return this.steps[stepIndex]
      }
      return null
    },

    // 移除步骤
    removeStep(stepIndex) {
      if (stepIndex >= 0 && stepIndex < this.steps.length) {
        const removedStep = this.steps.splice(stepIndex, 1)[0]
        
        // 重新编号后续步骤
        for (let i = stepIndex; i < this.steps.length; i++) {
          this.steps[i].stepNumber = i + 1
        }
        
        this.metadata.totalSteps = this.steps.length
        
        // 触发步骤删除事件
        if (typeof window !== 'undefined') {
          const event = new CustomEvent('stepDeleted', {
            detail: {
              index: stepIndex,
              step: removedStep
            }
          })
          document.dispatchEvent(event)
        }
        
        return removedStep
      }
      return null
    },

    // 移动步骤
    moveStep(fromIndex, toIndex) {
      if (fromIndex >= 0 && fromIndex < this.steps.length && 
          toIndex >= 0 && toIndex < this.steps.length && 
          fromIndex !== toIndex) {
        
        const step = this.steps.splice(fromIndex, 1)[0]
        this.steps.splice(toIndex, 0, step)
        
        // 重新编号所有步骤
        this.steps.forEach((step, index) => {
          step.stepNumber = index + 1
        })
        
        // 触发步骤移动事件
        if (typeof window !== 'undefined') {
          const event = new CustomEvent('stepMoved', {
            detail: {
              fromIndex,
              toIndex,
              step
            }
          })
          document.dispatchEvent(event)
        }
        
        return true
      }
      return false
    },

    // 更新步骤（通过步骤号）
    updateStepByNumber(stepNumber, updates) {
      const stepIndex = this.steps.findIndex(step => step.stepNumber === stepNumber)
      if (stepIndex !== -1) {
        this.steps[stepIndex] = { ...this.steps[stepIndex], ...updates }
        return this.steps[stepIndex]
      }
      return null
    },

    // 删除步骤（通过步骤号）
    removeStepByNumber(stepNumber) {
      const stepIndex = this.steps.findIndex(step => step.stepNumber === stepNumber)
      if (stepIndex !== -1) {
        return this.removeStep(stepIndex)
      }
      return null
    },


    // 移动步骤
    moveStep(fromIndex, toIndex) {
      if (fromIndex >= 0 && fromIndex < this.steps.length && 
          toIndex >= 0 && toIndex < this.steps.length && 
          fromIndex !== toIndex) {
        
        // 移除原位置的步骤
        const [movedStep] = this.steps.splice(fromIndex, 1)
        
        // 插入到新位置
        this.steps.splice(toIndex, 0, movedStep)
        
        // 重新编号所有步骤
        this.steps.forEach((step, index) => {
          step.stepNumber = index + 1
        })
      }
    },

    // 辅助方法：提取URL
    extractUrl(line) {
      const match = line.match(/page\.goto\(['"`]([^'"`]+)['"`]\)/)
      return match ? match[1] : ''
    },

    // 辅助方法：提取选择器
    extractSelector(line) {
      const match = line.match(/page\.\w+\(['"`]([^'"`]+)['"`]/)
      return match ? match[1] : ''
    },

    // 辅助方法：提取填充参数
    extractFillParams(line) {
      const match = line.match(/page\.(fill|type)\(['"`]([^'"`]+)['"`],\s*['"`]([^'"`]+)['"`]\)/)
      return match ? { selector: match[2], value: match[3] } : { selector: '', value: '' }
    },

    // 辅助方法：提取断言
    extractAssertion(line) {
      return line.trim()
    }
  }
})
